import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Servlet5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies=request.getCookies();
        int len=0;
        String lastAccessTime=null;
        if(cookies!=null) len=cookies.length;
        for (int i = 0; i < len; i++) {
            if(cookies[i].getName().equals("lastAccess")){
               lastAccessTime=cookies[i].getValue();
               lastAccessTime=URLDecoder.decode(lastAccessTime,"UTF-8");
               break;
            }
        }
        response.setContentType("text/html;charset=utf-8");
        if(lastAccessTime!=null){
            response.getWriter().print("欢迎再次访问本网站,上一次访问时间是："+lastAccessTime);
        }else {
            response.getWriter().print("这是您第一次访问本网站");
        }
        Date currentTime=new Date();
        String currentTimeString=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(currentTime);
//        日期时间转换字符串指定格式：
        System.out.println(currentTimeString);
        currentTimeString=URLEncoder.encode(currentTimeString,"utf-8");//把日期字符串添加到cookie里面，还需要单独编码
        Cookie cookie=new Cookie("lastAccess","a b c");
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
